/*
 * @Author: 江舟
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-05-23 16:11:01
 * @Description: file content
 */
import CryptoJS from 'crypto-js';
import smCrypto from 'sm-crypto';

const { sm4 } = smCrypto;
const md5 = CryptoJS.MD5;
const { enc } = CryptoJS;

class EnOrDecrypt {
    private key: string;
    constructor() {
        this.key = this.getEnKey();
    }
    getEnKey(timeStamp = '1716435471029', transId = 'gGjb624gBq3wMzqVMCRoC'): string {
        return md5(String(timeStamp) + transId).toString(enc.Hex);
    }
    // 加密
    encryptFunc(data) {
        let encrypted;
        if (typeof data === 'string') {
            encrypted = sm4.encrypt(data, this.key);
        } else if (typeof data === 'object') {
            // 对象格式的转成json字符串
            encrypted = sm4.encrypt(JSON.stringify(data), this.key);
        }
        if (encrypted) {
            return encrypted;
        }
        return '';
    }
    // 解密
    decipherFunc(data) {
        const decryptedStr = sm4.decrypt(data, this.key);
        try {
            return decryptedStr ? JSON.parse(decryptedStr) : '';
        } catch (error) {
            return decryptedStr;
        }
    }
}

export default EnOrDecrypt;
